<?php
namespace app\api\controller;


use app\api\model\Cart;
use app\api\validate\CartAddValidate;
use app\api\middleware\Auth;
use think\exception\ValidateException;
use app\api\validate\CartRemoveValidate;
use app\api\validate\CartChangeValidate;
use app\BaseController;

class CartController extends BaseController
{
	protected $middleware = [Auth::class];

	// 用户批量商品添加购物车
	public function addAll(Cart $model)
	{
		$carts = $this->request->param('carts/a',[]);
		if(empty($carts)){
			return $this->returnJson('购物车数据需要数组格式|500');
		}
		foreach($carts as $value){
			$model->addCart($this->request->userInfo->id,$value['goodsId'],$value['goodsCount']);
		}
		return $this->returnJson(SUCCESS_MESSAGE,[]);
	}
	// 添加商品到购物车
	public function add(Cart $model)
	{
		try {
            $data = $this->request->param();
            validate(CartAddValidate::class)->check($data);
  
            $cart = $model->addCart($this->request->userInfo->id,$data['goodsId'],$data['goodsCount']);
            return $this->returnJson(SUCCESS_MESSAGE,$cart);
        } catch (ValidateException $e) {
            return $this->returnJson($e->getError());
        }
	}

	// 移除购物车指定商品
	public function remove(Cart $model)
	{
		try {
            $data = $this->request->param();
            validate(CartRemoveValidate::class)->check($data);
  
            $model->find($data['cartId'])->delete();
            return $this->returnJson(SUCCESS_MESSAGE,[]);
        } catch (ValidateException $e) {
            return $this->returnJson($e->getError());
        }
	}

	// 清空购物车商品
	public function clear(Cart $model)
	{
		$model->where('user_id',$this->request->userInfo->id)->delete();
        return $this->returnJson(SUCCESS_MESSAGE,[]);
	}

	// 修改购物车商品数量
	public function change(Cart $model)
	{
		try {
            $data = $this->request->param();
            validate(CartChangeValidate::class)->check($data);
			$cart = $model->changeCart($data['cartId'],$data['goodsId'],$data['goodsCount']);
            return $this->returnJson(SUCCESS_MESSAGE,$cart);
        } catch (ValidateException $e) {
            return $this->returnJson($e->getError());
        }
	}

	// 获取用户的购物车数据
	public function lists(Cart $model)
	{
		$cartIds = $this->request->param('cartIds','');
		if($cartIds){
			$goods = $model->where('user_id','=',$this->request->userInfo->id)->where('id','in',$cartIds)->with(['goods'])->select();
		}else{
			$goods = $model->where('user_id','=',$this->request->userInfo->id)->with(['goods'])->select();
		}

		return $this->returnJson(SUCCESS_MESSAGE,$goods,count($goods));
	}
}